import React, { useEffect, useState, useRef, useMemo } from 'react';
import { NavigationProp, RouteProp } from '@react-navigation/native';
import { StyleSheet, TouchableOpacity, View, Text, Image, TextInput, Button, Alert } from 'react-native';
import { useSelector } from 'react-redux';
import { CommonStyle } from '../../../common/commonStyle.ts';
import { Loading } from '../../../component/LoadingOverlay.tsx';
import { AppDispatch, RootState } from '../../../redux/store.ts';
import AntDesign from 'react-native-vector-icons/AntDesign';
import HomeRequest from '../../../request/homeRequest.ts';
import CustomFlatList from '../../../component/CustomFlatList.tsx';
import { useReactive } from 'ahooks';
import { Badge, Actionsheet, useDisclose, useToast } from 'native-base';
import { ShowConfirmDialog } from '../../../component/ConfirmDialog.tsx';

interface IActivityApplyProps {
  navigation: NavigationProp<any, 'activityApply'>;
  route: RouteProp<{ activityApply: any }, 'activityApply'>;
}

interface IBuyType {
  eventId: number;
  beeperId: number;
  id: number;
  btnType: number;
  classifyIds: string;
  queryType: string | number;
  btnName: string;
  linkUrl: string;
  orderSource: number;
  sourceId: number;
  attr?: any;
  goods: IGetActivityGoodsByBtnList['goods'];
  addressInfo: IGetBtnDefaultGoodsRes['addressInfo'];
}

interface IData {
  pageNo: number;
  pageSize: number;
  secondClassifyIds?: string;
  beeperId: number;
  list: IActivityListIsList[];
  total: number;
  refreshing: boolean;
  isLoading: boolean;
  tempData?: IActivityListIsList;
  colorContainer: string[];
  btnList: any[];
  //以下5个字段后续通过全局属性拿取，目前暂时写固定值
  linkUrl: string;
  btnId: number;
  btnType: string | number;
  queryType: string | number;
  addressType: string | number;
  buyType?: IBuyType;
}

const ActivityApply: React.FC<IActivityApplyProps> = ({ navigation, route }) => {
  const btnInformation = useSelector((state: RootState) => state.btnInformation); //按钮里面的数据
  const beeperId = useSelector((state: RootState) => state.beeperId);
  const { isOpen, onOpen, onClose } = useDisclose();
  const toast = useToast();
  const data = useReactive<IData>({
    pageNo: 1,
    pageSize: 10,
    secondClassifyIds: btnInformation?.classifyIds, //这个参数需要从按钮点击传进来
    beeperId: beeperId,
    list: [],
    total: 1,
    refreshing: false,
    isLoading: false,
    colorContainer: ['#07C160', '#1989FA', '#8148AD', '#FF9FB7', '#FF976A'],
    btnList: [],
    linkUrl: '',
    btnId: btnInformation!.id,
    btnType: 1,
    queryType: 1,
    addressType: 2,
    buyType: undefined,
  });

  const fetchActivityList = () => {
    Loading.show('加载中');
    const { pageNo, pageSize, secondClassifyIds, beeperId } = data;
    if (data.pageNo <= data.total) {
      data.isLoading = true;
      HomeRequest.GetActivityList({ pageNo, pageSize, secondClassifyIds, beeperId })
      .then((res) => {
        Loading.hide();
        data.list = [...data.list, ...res.data.list];
        data.list.forEach((item) => {
          if (item.activityType === 2) {
            item.list.forEach((item2) => item2.selected && (item.selectedName = item2.btnName));
          }
        });
        data.total = res.data.totalPage;
        data.pageNo += 1;
        data.isLoading = false;
        data.refreshing = false;
      })
      .catch((err) => {
        data.isLoading = false;
        data.refreshing = false;
        Loading.hide();
      });
    } else {
          Loading.hide();
        }
   
  };

  // useEffect(() => {
  //   fetchActivityList();
  // }, []);

  const handleToActivityDetails = (item: IActivityListIsList) => {
    navigation.navigate('activityDetail', { id: item.activityId });
  };

  /**
   * 列表刷新
   */
  const customListRefresh = () => {
    data.refreshing = true;
    data.pageNo = 1;
    data.total = 1;
    data.list = [];
    fetchActivityList();
  };

  // 活动按钮事件
  const activityBtnChange = (item?: IActivityListIsList, childs?: any, event?: any) => {
    event.stopPropagation();
    // childs为真进入通知逻辑 否则进入产品按钮逻辑
    if (!childs) {
      data.tempData = item!;
      const { activityId, list, activityType } = data.tempData;
      let res: any = list;
      // 产品类型
      if (activityType === 1) {
        Loading.show('正在加载中');
        HomeRequest.ActivityListChildBtn({ activityId })
          .then((cdres) => {
            Loading.hide();
            console.log(cdres, 'cdres');
            res = cdres.data;
            if (Array.isArray(res) && res.length > 1) {
              res.forEach((cdItem, cdIndex) => {
                cdItem.color = data.colorContainer[cdIndex];
              });
              data.btnList = res;
              onOpen();
            } else if (Array.isArray(res) && res.length === 1) {
              // 如果没有按钮后端会抛出异常所以不用判断没有的情况
              // clickBtn({ currentTarget: { dataset: { item: res[0] } } });
              activityBtnChange(item, res[0], event);
              return;
            }
          })
          .catch((err) => {
            Loading.hide();
          });
      } else {
        if (Array.isArray(res)) {
          res.forEach((cdItem, cdIndex) => (cdItem.color = data.colorContainer[cdIndex]));
          data.btnList = res;
          onOpen();
        }
      }
    } else {
      const { activityServerId, btnName } = childs;
      const activityid = item!.activityId;
      const { beeperId, addressType, secondClassifyIds, btnId, btnType, queryType, list, linkUrl } = data;
      const { buyWay, activityType, activityId } = data.tempData || {};
      let res: any = '';
      if (activityType == 1) {
        // 产品类型
        Loading.show('正在加载中');
        HomeRequest.GetActivityGoodsByBtn({ activityServerId, beeperId })
          .then((resg) => {
            Loading.hide();
            const { goods, addressInfo, attr } = resg.data;
            if (buyWay == 13 || buyWay == 14) {
              // clearShopCartStorage()  清空购物车方法
            }
            const buyType: any = {
              eventId: buyWay,
              beeperId,
              id: btnId,
              btnType,
              classifyIds: secondClassifyIds,
              queryType,
              btnName,
              linkUrl,
              orderSource: 5, // 这里的orderSource为5表示活动下单
              sourceId: activityId,
              attr,
              goods: { ...goods, nums: 1 },
              addressInfo: { ...addressInfo, addressType },
            };
            data.buyType = buyType;
          })
          .catch((err) => {
            Loading.hide();
          });
      } else {
        /**
         * 只要activityType不为1就是通知类型，
         * 因为如果是三个按钮在列表中都显示出来了是获取不到tempData的，
         * 这个时候tempData会是空
         */
        ShowConfirmDialog({ title: '提示', message: '是否确认修改为当前按钮', confirmText: '确定', cancelText: '取消' }).then(() => {
          Loading.show('修改中...');
          HomeRequest.SetActivityRecord({ activityId: activityid || activityId, btnName })
            .then((ress) => {
              Loading.hide();
              onClose();
              toast.show({ description: '修改成功', duration: 1000 });
              list.find((itemE) => itemE.activityId == (activityid || activityId) && (itemE.selectedName = btnName));
            })
            .catch(() => Loading.hide());
        });
      }
    }
    /*
     *          {id:11,name:"弹框免支付下单"},
     *          {id:12,name:"弹框支付下单"},
     *          {id:13,name:"详情页下单"},
     *           {id:13,name:"结算页下单"},
     */
  };

  // 根据特定状态返回按钮展示
  const btnStateShow = (item: IActivityListIsList) => {
    if (item.activityType === 1 || item.selectedName) {
      return (
        <View style={styles.btnView1}>
          <View>
            {item.activityType === 1 && item.purchaseState && (
              <Badge colorScheme="error" alignSelf="center" variant={'solid'}>
                已购
              </Badge>
            )}
            {item.activityType === 2 && (
              <Badge colorScheme="error" alignSelf="center" variant={'outline'}>
                {item.selectedName}
              </Badge>
            )}
          </View>
          <View>
            <TouchableOpacity
              style={styles.btnClass}
              onPress={(event: any) => {
                activityBtnChange(item, '', event);
              }}
            >
              <Text style={{ color: 'white', fontWeight: 'bold' }}>{item.activityType === 1 ? item.mainBtnName : '修改'}</Text>
            </TouchableOpacity>
          </View>
        </View>
      );
    } else {
      return (
        <View style={{ flexDirection: 'row', justifyContent: 'flex-end' }}>
          {item.list.map((childs, indexs) => (
            <TouchableOpacity
              key={indexs}
              style={styles.btnClass}
              onPress={(event: any) => {
                activityBtnChange(item, childs, event);
              }}
            >
              <Text style={{ color: 'white', fontWeight: 'bold' }}>{childs.btnName}</Text>
            </TouchableOpacity>
          ))}
        </View>
      );
    }
  };

  const renderItem = (item: IActivityListIsList, index: number) => {
    return (
      <View>
        <TouchableOpacity onPress={() => handleToActivityDetails(item)} key={index} style={styles.list}>
          <Image
            style={styles.bgImg}
            source={{
              uri: item.mainImage,
            }}
          />
          <View style={styles.menus}>
            <View>
              <Text style={styles.title}>{item.activityName}</Text>
            </View>
            <View>
              <Text style={styles.describe}>{item.introduce}</Text>
            </View>
            <View>{btnStateShow(item)}</View>
          </View>
        </TouchableOpacity>
      </View>
    );
  };

  return (
    <View>
      <CustomFlatList data={data.list} style={{ paddingHorizontal: 16 }} renderItem={({ item, index }) => renderItem(item, index)} refreshing={data.refreshing} isLoading={data.isLoading} onEndReached={fetchActivityList} onRefresh={customListRefresh} />
      <Actionsheet isOpen={isOpen} onClose={onClose}>
        <Actionsheet.Content>
          {data.btnList.map((btns, btnIndex) => (
            <Actionsheet.Item
              onPress={(event) => {
                activityBtnChange(undefined, btns, event);
              }}
              key={btnIndex}
            >
              <Text style={{ color: btns.color }}>{btns.btnName}</Text>
            </Actionsheet.Item>
          ))}
        </Actionsheet.Content>
      </Actionsheet>
    </View>
  );
};

const styles = StyleSheet.create({
  list: {
    backgroundColor: 'white',
    marginTop: 20,
    borderRadius: 8,
  },
  bgImg: {
    width: '100%',
    minHeight: 160,
  },
  menus: {
    backgroundColor: '#fff',
    minHeight: 120,
    borderBottomRightRadius: 8,
    borderBottomLeftRadius: 8,
    padding: 10,
  },
  title: {
    color: '#000',
    fontSize: 16,
    marginBottom: 10,
  },
  describe: {
    color: '#ccc',
    fontSize: 14,
    marginBottom: 20,
  },
  btnView1: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  btnClass: {
    width: 'auto',
    minWidth: 80,
    paddingHorizontal: 10,
    height: 34,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 8,
    backgroundColor: CommonStyle.mainColor,
    marginHorizontal: 4,
  },
});

export default ActivityApply;
